import axios, { AxiosRequestConfig, AxiosResponse, AxiosError, InternalAxiosRequestConfig } from '@ohos/axios';

// 定义 API 响应数据的类型
export interface ApiResponse {
  data: string;
  message: string;
  status: number;
}

// 创建一个 axios 实例
const instance = axios.create({
  baseURL: 'https://m.maizuo.com', // 替换成你的 API 基本 URL
  timeout: 5000, // 请求超时时间
  headers: {
    'X-Client-Info': '{"a":"3000", "ch":"1002","v":"5.0.4", "e":"1596502176387264316178433","bc":"310100"}',
    "X-Host":"mall.film-ticket.film.list"
  }
});

// 请求拦截器
instance.interceptors.request.use(
  (config: InternalAxiosRequestConfig): InternalAxiosRequestConfig => {
    const token: string | null = getToken(); // 假设 getToken() 是一个获取 token 的方法
    if (token) {
      config.headers['authorization'] = `${token}`;
    }
    return config;
  },
  (error: AxiosError): Promise<AxiosError> => {
    return Promise.reject(error);
  }
);

// 响应拦截器
instance.interceptors.response.use(
  (response: AxiosResponse): AxiosResponse => {
    // 自定义响应数据结构
    // 返回符合 AxiosResponse 结构的对象
    return response.data
  },
  (error: AxiosError): Promise<string> => {
    return Promise.reject(error.toJSON());
  }
);

// 封装的 API 请求方法
export const http = {
  get(url: string, params: Record<string, string | number | boolean> = {}, config: AxiosRequestConfig = {}): Promise<AxiosResponse> {
    return instance.get<ApiResponse, AxiosResponse<ApiResponse>>(url, { params, ...config });
  },

  post(url: string, data: Record<string, string | number | boolean> = {}, config: AxiosRequestConfig = {}): Promise<AxiosResponse> {
    return instance.post<ApiResponse, AxiosResponse<ApiResponse>>(url, data, config);
  },

  put(url: string, data: Record<string, string | number | boolean> = {}, config: AxiosRequestConfig = {}): Promise<AxiosResponse> {
    return instance.put<ApiResponse, AxiosResponse<ApiResponse>>(url, data, config)
  },

  delete(url: string, config: AxiosRequestConfig = {}): Promise<AxiosResponse> {
    return instance.delete<ApiResponse, AxiosResponse<ApiResponse>>(url, config)
  },
};

// 获取 token (示例)
function getToken(): string | null {
  return 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MiwiaWF0IjoxNzM3MzYwMzcwLCJleHAiOjE3Mzc5NjUxNzB9.KNR1B5TjcJtd5Ro11Ji46P7fTvQGQ7rHlgVB8Vnq9yA'
}
